package net.alteiar.algorithms;

import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

import net.alteiar.images.metadata.ImageInfo;

public class RayCast {

	public static void line(ImageInfo info, Point begin, Point end, int value) {
		int w = end.x - begin.x;
		int h = end.y - begin.y;
		int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
		if (w < 0)
			dx1 = -1;
		else if (w > 0)
			dx1 = 1;
		if (h < 0)
			dy1 = -1;
		else if (h > 0)
			dy1 = 1;
		if (w < 0)
			dx2 = -1;
		else if (w > 0)
			dx2 = 1;
		int longest = Math.abs(w);
		int shortest = Math.abs(h);
		if (!(longest > shortest)) {
			longest = Math.abs(h);
			shortest = Math.abs(w);
			if (h < 0)
				dy2 = -1;
			else if (h > 0)
				dy2 = 1;
			dx2 = 0;
		}

		int x = begin.x;
		int y = begin.y;
		int numerator = longest >> 1;
		for (int i = 0; i <= longest; i++) {
			info.setValue(x, y, value);

			numerator += shortest;
			if (!(numerator < longest)) {
				numerator -= longest;
				x += dx1;
				y += dy1;
			} else {
				x += dx2;
				y += dy2;
			}
		}
	}

	public static List<Point> line(Point begin, Point end) {
		List<Point> pts = new ArrayList<>();

		int w = end.x - begin.x;
		int h = end.y - begin.y;
		int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0;
		if (w < 0)
			dx1 = -1;
		else if (w > 0)
			dx1 = 1;
		if (h < 0)
			dy1 = -1;
		else if (h > 0)
			dy1 = 1;
		if (w < 0)
			dx2 = -1;
		else if (w > 0)
			dx2 = 1;
		int longest = Math.abs(w);
		int shortest = Math.abs(h);
		if (!(longest > shortest)) {
			longest = Math.abs(h);
			shortest = Math.abs(w);
			if (h < 0)
				dy2 = -1;
			else if (h > 0)
				dy2 = 1;
			dx2 = 0;
		}

		int x = begin.x;
		int y = begin.y;
		int numerator = longest >> 1;
		for (int i = 0; i <= longest; i++) {
			pts.add(new Point(x, y));

			numerator += shortest;
			if (!(numerator < longest)) {
				numerator -= longest;
				x += dx1;
				y += dy1;
			} else {
				x += dx2;
				y += dy2;
			}
		}

		return pts;
	}
}
